package com.sympsel;

import org.junit.Test;

public class Others {

    public int removeDuplicates1(int[] nums) {
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            while (i + 2 < len && nums[i + 1] == nums[i] && nums[i + 2] == nums[i]) {
                len--;
                for (int j = i + 2; j < len; j++) {
                    nums[j] = nums[j + 1];
                }
            }
        }
        return len;
    }

    public int removeDuplicates2(int[] nums) {
        int len = nums.length;
        int left = 0, right = 0, maxCount = 2, rightFixed = 0;
        while (right < len) {
            if (nums[right] != nums[left]) {
                left = right;
                maxCount = 2;
            }
            while (right < len && nums[right] == nums[left]) {
                maxCount--;
                right++;
                if (maxCount == 0) {
                    rightFixed = right;
                }
            }
            if (maxCount < 0) {
                len += maxCount;
                for (int i = rightFixed, j = right; i < len; i++, j++) {
                    nums[i] = nums[j];
                }
                right = rightFixed;
            }
        }
        return len;
    }

    public int removeDuplicates3(int[] nums) {
        int len = nums.length, writeIndex = 0, readIndex = 0;
        while (readIndex < len) {
            int val = nums[readIndex];
            int cnt = 0;
            while (readIndex < len && nums[readIndex] == val) {
                cnt++;
                readIndex++;
            }

            int keep = Math.min(cnt, 2);
            for (int i = 0; i < keep; i++) {
                nums[writeIndex++] = val;
            }
        }
        return writeIndex;
    }

    public int removeDuplicates4(int[] nums) {
        int slow = 0;
        for (int fast = 0; fast < nums.length; fast++) {
            if (slow < 2 || nums[fast] != nums[slow - 2]) {
                nums[slow++] = nums[fast];
            }
        }
        return slow;
    }

    @Test
    public void test1() {
//        int[] nums = {1, 1, 1, 2, 2, 3};
//        int[] nums = {0, 0, 1, 1, 1, 1, 2, 3, 3};
        int[] nums = {1, 1, 1, 2, 2, 2, 3, 3};
        int newLen = removeDuplicates4(nums);
        for (int i = 0; i < newLen; i++) {
            System.out.print(nums[i] + " ");
        }
        System.out.println();
    }



}
